class Vector2 {
    x: number;
    y: number;
    constructor(x = 0, y = 0) {
        this.x = x;
        this.y = y
    }
    // 相加
    add(v2: Vector2) {
        return new Vector2(v2.x + this.x, v2.y + this.y)
    }
    // 相减
    sub(v2: Vector2) {
        return new Vector2(this.x - v2.x, this.y - v2.y)
    }
    divided(n: number) {
        return new Vector2(this.x / n, this.y / n)
    }
}

// 放大背景图的尺寸
let zoomBackgroundImageWidth = 750
let zoomBackgroundImageHeight = 1000

// 获取图片相关尺寸
const img = document.querySelector('img')
const width = img?.offsetWidth
const height = img?.offsetHeight
const imgSize = new Vector2(width, height)

// 图片左上角距离父元素的位置
const imgLeft = img?.offsetLeft
const imgTop = img?.offsetTop
const LT = new Vector2(imgLeft, imgTop)
// 图片右下角位置
const RB = LT.add(imgSize)

const imgParent = document.querySelector('.product-img') as any;
const parentPos = new Vector2(imgParent.offsetLeft, imgParent.offsetTop)

// zoom图层信息
const zoom = document.querySelector('.zoom') as HTMLDivElement;
const zoomSize = new Vector2(zoom.offsetWidth, zoom.offsetHeight)

// 移动模块相关参数
const tools = document.querySelector('.tools') as HTMLDivElement;
const toolsLeft = tools.offsetLeft;
const toolsTop = tools.offsetTop;

const toolsWidth = zoomSize.x / zoomBackgroundImageWidth * imgSize.x
const toolsHeight = zoomSize.y / zoomBackgroundImageHeight * imgSize.y
tools.style.width = toolsWidth + 'px'
tools.style.height = toolsHeight + 'px'
const toolsSize = new Vector2(toolsWidth, toolsHeight)
console.log(parentPos);


// 图片右下角限制
const RBRange = RB.sub(toolsSize)
// 限制范围
const limitRange = (pos: Vector2): Vector2 => {
    let { x, y } = pos

    x = x >= LT.x ? x : LT.x
    y = y >= LT.y ? y : LT.y

    x = x <= RBRange.x ? x : RBRange.x
    y = y <= RBRange.y ? y : RBRange.y
    // const flag = x >= LT.x && y >= LT.y && x <= RB.x && y <= RB.y
    return new Vector2(x, y)
}

const getScale = () => {
    // 改变左右位置
    const left = tools.offsetLeft - (img?.offsetLeft || 0)
    const scaleX = left / imgSize.x
    const x = scaleX * zoomBackgroundImageWidth
    zoom.style.backgroundPositionX = -x + 'px'

    // 改变上下位置
    const top = tools.offsetTop - (img?.offsetTop || 0)
    const scaleY = top / imgSize.y
    const y = scaleY * zoomBackgroundImageHeight
    zoom.style.backgroundPositionY = -y + 'px'
}

// 鼠标位置
const mouseMove = (e: any) => {
    tools.style.display = 'block'
    zoom.style.visibility = 'visible'
    // 获取当前鼠标位置
    const mouse = new Vector2(e?.clientX, e?.clientY);
    // console.dir(mouse);
    // 鼠标当前位置-父元素距离页面位置-模块尺寸的一半
    const toolsPosition = mouse.sub(parentPos).sub(toolsSize.divided(2))

    const pos = limitRange(toolsPosition)

    getScale()

    tools.style.left = pos.x + 'px'
    tools.style.top = pos.y + 'px'

}





if (imgParent) {
    imgParent.onmousemove = mouseMove
    imgParent.onmouseleave = ()=>{
        tools.style.display = 'none'
        zoom.style.visibility = 'hidden'
    }
}

